package cn.virens.http;

import java.util.HashMap;

import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.server.util.Resps;

import cn.virens.exception.ExceptionUtil;

public class ResultText extends HashMap<String, Object> {
	private static final long serialVersionUID = -5278704552361012772L;

	private final HttpRequest request;

	private ResultText(HttpRequest request) {
		this.request = request;
	}

	public static ResultText of(HttpRequest request) {
		return new ResultText(request);
	}

	public static HttpResponse of(HttpRequest request, ResultSupplier supplier) {
		return of(request).data(supplier);
	}

	public HttpResponse data(ResultSupplier supplier) {
		try {
			// 执行请求操作，并返回对应的响应内容
			return Resps.txt(request, supplier.apply());
		} catch (Exception e) {
			return Resps.txt(request, ExceptionUtil.getCode(e));
		}
	}

	public HttpResponse response() {
		return Resps.json(request, toString());
	}

	@FunctionalInterface
	public interface ResultSupplier {
		String apply() throws Exception;
	}
}
